package com.orkasgb.framework.springsecurity.usernamepassword;

import com.orkasgb.framework.springsecurity.CommonResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 自定义成功处理器，用于处理登录成功的情况。
 * <p>
 * 仅将成功消息提供给前端，不受其他现有处理器的影响。
 */
@Component("orkasgbSuccessHandle")
public class OrkasgbSuccessHandle implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.displayName());
        response.setHeader(HttpHeaders.AUTHORIZATION, request.getAttribute("accessToken").toString());
        response.getWriter().write(CommonResult.ofSuccess(authentication, "登录成功！").toString());
    }
}
